/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:08:34
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-20 09:39:15
 */
import React from 'react';
import { WeaTools } from 'ecCom';
import { Spin } from 'antd';

const { viewer } = WeaTools;
const f = v =>
  v.replace(
    /<a[^>]*[^>]*>(.*?)<\/a>/g,
    m => `<a target="_blank" ${m.slice(3)}`,
  );

export default class ContentIframe extends React.Component {
  static filter = f;
  constructor(props) {
    super(props);
    this.isInstanceMounted = false;
    this.prefixClass = 'wea-email-content-iframe';
    this.id = `weaEmailContentIframe_${Math.random()
      .toString(36)
      .substr(2, 6)}`;
    this.state = {
      height: 0,
      loadIframe: true,
      loading: false,
    };
  }
  componentDidMount() {
    this.isInstanceMounted = true;
    const { value } = this.props;
    this.setContent(value, true);
  }
  componentWillReceiveProps(nextProps) {
    const { value: _value } = this.props;
    const { value } = nextProps;
    if (_value !== value) {
      // need reload iframe and reset height twice to set body height auto
      this.setState({ loadIframe: false, height: 0 }, () => {
        this.setState({ loadIframe: true, height: 0 }, () => {
          this.setContent(value, _value !== value);
        });
      });
    }
  }
  componentWillUnmount() {
    this.isInstanceMounted = false;
  }
  setContent(value, init) {
    const frame = this.refs.content;
    const win = frame.contentWindow;
    const doc = win.document;
    if (typeof value === 'string') {
      init &&
        doc.write(
          '<html><head><style>table{border-collapse: collapse;}</style></head><body style="overflow-y:hidden"></body></html>',
        );
      doc.body.innerHTML = f(value);
    }
    // get height while imgs all loaded
    const imgs = doc.getElementsByTagName('img');
    /* eslint-disable */
    let imgLoaded = 0;
    /* eslint-enable */
    this.setState({ loading: true });
    const onOk = () => {
      imgLoaded++;
      // if (imgLoaded === imgs.length || imgs.length === 0) {
      const { scrollHeight = 0, offsetHeight = 0 } = doc.documentElement;
      // + 20 for overflow-x scrollbar
      this.setState({
        height: (scrollHeight || offsetHeight) + 20,
        loading: false,
      });
      // }
    };
    onOk();
    // !imgs || imgs.length === 0 ? onOk()
    // :
    if (imgs && imgs.length > 0) {
      Array.prototype.forEach.call(imgs, (img) => {
        const i = img;
        i.onload = () => {
          i.setAttribute('data-imgsrc', img.src);
          i.setAttribute('class', 'formImgPlay');
          onOk();
        };
        i.onclick = viewer;
        i.onerror = onOk;
      });
    }
    if (init) {
      const { onClick } = this.props;
      const eventHander = ['onclick', 'ondblclick', 'contextmenu'];
      eventHander.forEach((h) => {
        doc.documentElement[h] = () => {
          typeof onClick === 'function' && onClick();
        };
      });
    }
  }
  render() {
    const { height, loadIframe, loading } = this.state;
    return (
      <Spin
        ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@f3oscn`}
        spinning={loading}
      >
        {loadIframe ? (
          <iframe
            id={this.id}
            ref="content"
            src="javascript:document.open();document.close();"
            className={this.prefixClass}
            style={{ width: '100%', height }}
            title="email-view-iframe"
          />
        ) : null}
      </Spin>
    );
  }
}
